//
//  YHBaseCollectionView.swift
//  Adorbee
//
//  Created by amovision on 2024/11/27.
//

import UIKit
#if canImport(SnapKit)
import SnapKit
#endif

open class YHBaseCollectionView<T>: UICollectionView {
  public var dataArray = [Any]() {
    didSet {
      reloadData()
    }
  }

  public var isSectionCell: Bool = false
  private var modelArray: [[T]] {
    if let dataList = dataArray as? [T] {
      return isSectionCell ?dataList.map { [$0] }:[dataList]
    }
    if let dataList = dataArray as? [[T]] {
      return dataList
    }
    return []
  }

  public func attach(on vc: YHBaseViewController, _ insets: UIEdgeInsets = .zero) {
    vc.view.addSubview(self)
#if canImport(SnapKit)
    snp.makeConstraints { make in
      make.top.equalTo(vc.navigationBar.snp.bottom).offset(insets.top)
      make.left.equalTo(insets.left)
      make.right.equalTo(-insets.right)
      make.bottom.equalTo(-insets.bottom)
    }
#endif
  }
    
  open func model(_ section: Int, _ item: Int) -> T? {
    dataArray.isEmpty ?nil:modelArray[section][item]
  }
    
  public func reusableCell<C: YHBaseCollectionViewCell<T>>(_ section: Int, _ item: Int, type: C.Type? = nil, config: ((C, T?) -> Void)? = nil) -> C {
    let model = model(section, item)
    let cellType = type ?? (registerCells?.first as? C.Type)
    let cell = dequeueReusableCell(named: cellType!, section: section, item: item)
    if let model { cell.model = model }
    config?(cell, model)
    return cell
  }
    
  public override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    numOfRows?(section) ?? modelArray[section].count
  }
    
  public override func numberOfSections(in collectionView: UICollectionView) -> Int {
    numOfSections?() ?? modelArray.count
  }
    
  public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell = cellForRows?(indexPath.section, indexPath.item) {
      return cell
    } else {
      return reusableCell(indexPath.section, indexPath.item)
    }
  }
}

open class YHBaseCollectionViewCell<T>: UICollectionViewCell {
  public var eventBlock: ((Int) -> Void)?
    
  override public init(frame: CGRect) {
    super.init(frame: frame)
    initContent()
  }
    
  @available(*, unavailable)
  required public init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  open func initContent() {}
  open func initModel(_ model: T) {}
  public var model: T! {
    didSet {
      initModel(model)
    }
  }
}

public class YHCollectionReusableView: UICollectionReusableView {
  public var contentView: UIView? {
    didSet {
      if let contentView {
        oldValue?.removeFromSuperview()
        addSubview(contentView)
#if canImport(SnapKit)
        contentView.snp.makeConstraints { make in
          make.edges.equalToSuperview()
        }
#endif
      }
    }
  }
}
